<template>
	<view class="task-container">
		<!-- <view class="task-card">
			<view v-for="(item,index) in cardHeader" :key="index">
				<view class='task-item' :class="{'active':cardNum == index}" @click="changeCard(index,item.index)">
					{{item.name}}
				</view>
			</view>
		</view> -->
		<view class="task-content">
			<view class="task-empty" v-if="dataList.length === 0">
				<u-empty mode="history" text="暂无视频创建记录">
				</u-empty>
			</view>
			<view v-else>
				<scroll-view scroll-y="true" class="scroll-Y scroll_list" @scrolltolower="lower"
					:style="{ height: 'calc(100vh - 118px)' }">
					<view class="content-item" v-for="(item,index) in dataList" :key="index"
						@click="videoDetail(item.taskState,item.id)">
						<view class="content-item-icon">
							<u-icon name="hourglass-half-fill" size="28" color="#F97316"
								v-if="item.taskState == 2"></u-icon>
							<u-icon name="clock-fill" size="28" color="#3B82F6" v-if="item.taskState == 1"></u-icon>
							<u-icon name="info-circle-fill" size="28" color="#EF4444"
								v-if="item.taskState == 4"></u-icon>
							<!-- <u-icon name="pause" size="28" color="#6B7280" v-if="item.taskState == 1"></u-icon> -->
							<view class="img_item" style="width: 100%;" v-if="item.taskState == 3">
								<view class="iconfont icon-bofang1">

								</view>
								<u--image mode='aspectFill' :src="item.coverImg" width="100%" height="60px"></u--image>
							</view>
						</view>
						<view class="content-item-info">
							<view class="item-info-title">
								<view class="task-title">{{item.title}}</view>
								<view>
									<view v-if="item.taskState == 2" class="task-type prog">生成中</view>
									<view v-if="item.taskState ==1" class="task-type queue">排队中</view>
									<view v-if="item.taskState == 4" class="task-type error">已失败</view>
									<!-- <view v-if="item.type == 4" class="task-type load">等待中</view> -->
									<view v-if="item.taskState == 3" class="task-type success">已完成</view>
								</view>
							</view>
							<!-- item.taskProcess -->
							<view class="item-info-progress" v-show="item.taskProcess">
								<u-line-progress :percentage="item.taskProcess==100?99:item.taskProcess" height="14"
									activeColor="#F97316"></u-line-progress>
								<view class="progcess-desc">
									<view>{{item.taskProcess==100?99:item.taskProcess}}%已完成</view>
									<view>预计剩余:{{item.taskProcessTime=='00:00'?'00.01':item.taskProcessTime}}</view>
								</view>
							</view>
							<view v-show="!item.taskProcess">
								<view v-show="item.taskState == 1" class="item-info-font">当前队列位置:{{item.queuePosition}}
								</view>
								<view v-show="item.taskState == 4" class="item-info-font">生成失败</view>
								<!-- <view v-show="item.type == 4" class="item-info-font">等待资源分配</view> -->
								<view v-show="item.taskState == 3" class="item-info-font">视频制作完成</view>
							</view>

							<view class="item-info-font">{{item.insertTime}}</view>
						</view>
					</view>

					<view class="" style="height: 10px;">

					</view>
				</scroll-view>

			</view>

		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				cardNum: 0, //默认全部
				cardHeader: [{
					name: '全部',
					index: 0,
				}, {
					name: '已完成',
					index: 3,
				}, {
					name: '生成中',
					index: 2,
				}, {
					name: '排队中',
					index: 1,
				}, {
					name: '失败',
					index: 4,
				}, ],
				dataList: [

				],
				query: {
					pageNum: 1,
					pageSize: 10,
					taskState: null
				},
				timer: null, // taskState=1的定时器
			};
		},
		computed: {},
		components: {},

		onload() {

		},
		mounted() {
			this.tasklistfn()
		},
		watch: {

		},
		beforeDestroy() {
			this.clearTimers();
		},
		methods: {
			timelist() {
				// 检查是否需要请求特定状态的定时器
				const checkAndRequest = (timerKey) => {
					// 检查dataList中是否有对应状态的数据
					const hasStateData = this.checkTaskState1Or2();

					if (!hasStateData) {
						this.clearTimers()
						return;
					}

					// 如果定时器不存在，则创建
					if (!this[timerKey]) {
						this[timerKey] = setInterval(() => {
							// 再次检查是否还有对应状态的数据
							const hasStateData = this.checkTaskState1Or2();
							if (!hasStateData) {
								this.clearTimers()
								return;
							}

							this.makeRequest();
						}, 5000);
					}
				};

				// 初始检查并启动定时器
				checkAndRequest('timer');


				// // 启动监控
				// this.startMonitoring();
			},

			// 发起请求的方法
			makeRequest() {
				this.$request(`/task/listByPage`, 'post', this.query).then(res => {
					if (res && res.data && res.data.data && res.data.data.records && res.data.data.records.length >
						0) {
						console.log(`返回数据:`, res.data.data.records);
						// 更新dataList中的数据
						this.updateDataList(res.data.data.records);
					}
				}).catch(error => {
					console.log(error);
				});
			},

			// 更新dataList的方法
			updateDataList(newRecords) {
				if (!this.dataList || !newRecords) return;

				this.dataList = this.dataList.map(item => {
					// 只对taskState为1或2的项进行更新
					if (item.taskState === 1 || item.taskState === 2) {
						// 在newRecords中查找相同ID的项
						const matchedRecord = newRecords.find(record => record.id === item.id);
						// 如果找到匹配项，则替换；否则保持原样
						return matchedRecord ? {
							...matchedRecord
						} : item;
					} else {
						// taskState不是1或2的项保持不变
						return item;
					}
				});

				console.log('更新后的dataList:', this.dataList);
				const hasStateData = this.checkTaskState1Or2();

				if (!hasStateData) {
					this.clearTimers()
					return;
				}

			},
			// 清理定时器
			clearTimers() {
				if (this.timer) {
					clearInterval(this.timer);
					this.timer = null;
				}

			},
			// startMonitoring() {
			// 	// 每10秒检查一次是否需要启动或停止定时器
			// 	this.monitorTimer = setInterval(() => {
			// 		this.checkAndRequest(1, 'timer1');
			// 		this.checkAndRequest(2, 'timer2');
			// 	}, 10000);
			// },

			// // 单独封装的检查方法
			// checkAndRequest(taskState, timerKey) {
			// 	const hasStateData = this.dataList && this.dataList.some(item => item.taskState === taskState);

			// 	if (!hasStateData) {
			// 		if (this[timerKey]) {
			// 			clearInterval(this[timerKey]);
			// 			this[timerKey] = null;
			// 			console.log(`停止 taskState ${taskState} 的定时请求`);
			// 		}
			// 		return;
			// 	}

			// 	if (!this[timerKey]) {
			// 		console.log(`启动 taskState ${taskState} 的定时请求`);
			// 		this[timerKey] = setInterval(() => {
			// 			const currentHasStateData = this.dataList && this.dataList.some(item => item.taskState ===
			// 				taskState);
			// 			if (!currentHasStateData) {
			// 				clearInterval(this[timerKey]);
			// 				this[timerKey] = null;
			// 				console.log(`停止 taskState ${taskState} 的定时请求`);
			// 				return;
			// 			}
			// 			this.makeRequest(taskState);
			// 		}, taskState === 1 ? 5000 : 3000);
			// 	}
			// },
			tasklistfn() {
				this.$request(`/task/listByPage`, 'post', this.query).then(res => {
					this.dataList = res.data.data.records ? this.dataList.concat(res.data.data.records) : [];

					// 检查dataList中是否有taskState为1或2的项
					const hasTaskState1Or2 = this.checkTaskState1Or2();

					if (hasTaskState1Or2) {
						console.log('检测到taskState为1或2的项，调用timelist');
						this.timelist();
					} else {
						this.clearTimers()
						console.log('未检测到taskState为1或2的项，不调用timelist');
					}
				}).catch(error => {
					console.error('请求失败:', error);
				});
			},

			// 检查dataList中是否有taskState为1或2的项
			checkTaskState1Or2() {
				if (!this.dataList || this.dataList.length === 0) {
					return false;
				}
				return this.dataList.some(item => item.taskState === 1 || item.taskState === 2);
			},

			// timelist() {
			// 	const query = {
			// 		pageNum: 1,
			// 		pageSize: 10,
			// 		taskState: 1
			// 	}
			// 	this.$request(`/task/listByPage`, 'post', query).then(
			// 		res => {
			// 			console.log(res.data.data.records);
			// 		})
			// },
			lower() {
				this.query.pageNum++
				this.tasklistfn()
			},
			changeCard(num, e) {
				this.query.pageNum = 1
				this.query.taskState = e > 0 ? e : null
				this.dataList = []
				this.tasklistfn()
				this.cardNum = num;
			},
			videoDetail(type, id) {
				// this.clearTimers()
				const that = this
				const obj = {
					type: type,
					id: id
				}
				// 传值 当前卡片的状态
				uni.navigateTo({
					url: '/pages/video/video_detail?type=' + encodeURIComponent(JSON.stringify(obj)),
					// events: {
					// 	Data: (data) => {
					// 		if (data.data) {
					// 			that.query.pageNum = 1
					// 			that.dataList = []
					// 			that.makeRequest()
					// 		}
					// 	},
					// },



				})
			}
		}
	};
</script>

<style>
	.task-container {
		box-sizing: border-box;
		padding: 10px 10px 0 10px;
		margin-bottom: 60px;
		background-color: #f3f3f4;
		border-radius: 15px 15px 0 0;
		min-height: calc(100vh - 108px);
	}

	.task-card {
		width: calc(100% - 20px);
		height: auto;
		display: flex;
		justify-content: space-between;
		flex-wrap: wrap;
		/* margin-bottom: 10px; */
		background-color: #f9f9fa;
		padding: 0px 10px 10px;
	}

	.task-item {
		padding: 5px 13px;
		/* margin-right: 10px; */
		border-radius: 50px;
		font-size: 14px;
		box-shadow: 0 5px 5px -2px rgba(0, 0, 0, 0.5);
		color: #64748B;
		border-radius: 50px;
		/* background-color: #fff; */
		border: 1px solid #d3d3d3;
		transition: 0.5s;
	}

	.task-item.active {
		color: #F97316;
		font-weight: bold;
		border: 1px solid #F97316;
		box-shadow: 0 5px 5px -2px rgba(249, 115, 22, 0.5);
	}

	.task-content {
		width: 100%;
		height: auto;
	}

	.task-empty {
		width: 100%;
		height: 100vw;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.content-item {
		display: flex;
		width: 100%;
		height: auto;
		margin-bottom: 15px;
		border-radius: 10px;
		box-sizing: border-box;
		padding: 10px 10px;
		/* background-color: #ececec; */
		border: 1px solid #f4f4f4;
		box-shadow: 0 5px 5px -2px rgba(0, 0, 0, 0.5);

	}

	.content-item-icon {
		width: 60px;
		margin-right: 10px;
		display: flex;
		align-items: center;
		justify-content: center;

	}

	.img_item {
		position: relative;


	}

	.icon-bofang1 {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		z-index: 1000;
		color: rgba(232, 232, 232, 0.7);
	}

	.content-item-info {
		width: calc(100% - 70px);
		/* flex: 1; */
	}

	.item-info-title {
		width: 100%;
		height: 30px;
	}

	.item-info-title .task-title {
		float: left;
		width: 80%;
		font-size: 28rpx;
		color: #333;
		line-height: 30px;
		font-weight: 600;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.item-info-title .task-type {
		float: left;
		width: 20%;
		height: 25px;
		text-align: center;
		line-height: 25px;
		font-size: 22rpx;

		border-radius: 20px;

	}

	.item-info-progress {
		margin-top: 10px;
	}

	.progcess-desc {
		display: flex;
		justify-content: space-between;
		font-size: 14px;
		color: #64748B;
		margin-top: 5px;
	}

	.item-info-font {
		font-size: 14px;
		color: #64748B;
		margin-top: 5px;
	}

	.scroll_list {

		/* padding-bottom: 10px; */
		/* padding: 10px 0; */
	}

	::-webkit-scrollbar {
		width: 0px;
		/* 滚动条的宽度 */
	}
</style>

<style>
	.prog {
		color: #F97316;
		background-color: #FFEDD5;
	}

	.queue {
		color: #3B82F6;
		background-color: #DBEAFE;
	}

	.error {
		color: #EF4444;
		background-color: #FEE2E2;
	}

	.load {
		color: #6B7280;
		background-color: #E5E7EB;
	}

	.success {
		color: #fff;
		background-color: #67C23A;
	}
</style>